package com.heima.behavior.service.impl;

import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.entity.ApUser;
import com.heima.user.util.AppThreadLocalUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Date;

public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1. 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null && dto.getEquipmentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 查询用户阅读行为
        Criteria criteria = new Criteria()
                .orOperator(Criteria.where("userId").is(user.getId()),
                        Criteria.where("equipmentId").is(dto.getEquipmentId())
                                .andOperator(Criteria.where("articleId").is(dto.getArticleId())));

        ApReadBehavior readBehavior = mongoTemplate.findOne(Query.query(criteria), ApReadBehavior.class);

        if (readBehavior != null) {
            readBehavior.setCount(readBehavior.getCount());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setReadDuration(dto.getReadDuration());
            mongoTemplate.save(readBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //2.3.2 保存关注数据到数据库
        readBehavior = new ApReadBehavior();
        readBehavior.setReadDuration(dto.getReadDuration());
        readBehavior.setArticleId(dto.getArticleId());
        readBehavior.setCreatedTime(new Date());
        readBehavior.setCount(1);
        readBehavior.setUpdatedTime(new Date());
        readBehavior.setLoadDuration(dto.getLoadDuration());
        readBehavior.setPercentage(dto.getPercentage());
        readBehavior.setUserId(user.getId().longValue());
        readBehavior.setEquipmentId(dto.getEquipmentId());

        mongoTemplate.save(readBehavior);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
